<template>
  <a-modal :open="open" centered width="840px" title="屈光检查" :footer="null" @cancel="onCancel">
    <div class="p-8">
      <div v-if="open" class="flex justify-between items-center mb-4">
        <EyeCanvas ref="odRef" title="OD" />
        <EyeCanvas ref="osRef" title="OS" />
      </div>
      <div class="flex justify-end mt-6">
        <a-button class="mr-3" type="default" @click="clearCanvas">清屏</a-button>
        <a-button class="mr-2" type="primary" @click="onSave">保存</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import axios from 'axios'
import { message } from 'ant-design-vue'
import EyeCanvas from './EyeCanvas.vue'

const osRef = ref(null)
const odRef = ref(null)
const clearCanvas = () => {
  odRef.value.clear()
  osRef.value.clear()
}

// import usePatientsStore from '../../../store'

// const patientsStore = usePatientsStore()
defineProps({
  open: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['update:open', 'ok'])

const onSave = () => {
  const od = odRef.value.getData()
  const os = osRef.value.getData()
  getXml(base64toFile(od, 'od.png'), 'od')
  getXml(base64toFile(os, 'os.png'), 'os')
}
const getXml = async (file, type) => {
  const formData = new FormData()
  formData.append('file', file)
  const res = await axios.post('/api/v1/emr/emrTemplate/doInsertImageXML', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.data.code !== 0) return message.error(res.data.msg || '保存失败')
  emit('ok', res.data.data, type)
}
const onCancel = () => {
  emit('update:open', false)
}
const base64toFile = (base64Data, filename) => {
  const arr = base64Data.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
